package cn.sangyy.auth.controller;

import cn.sangyy.auth.annotation.Permission;
import cn.sangyy.auth.domain.Role;
import cn.sangyy.auth.query.RoleQuery;
import cn.sangyy.auth.service.IRoleService;
import cn.sangyy.basic.utils.AjaxResult;
import cn.sangyy.basic.utils.PageList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author SangYY
 * @date: 2023/05/17/16:15
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色管理")
@Permission(name = "角色管理",desc = "管理用户角色的接口")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    /**
    * @author Sangyy
    * 分页查找+高级搜索
    */
    @PostMapping
    @ApiOperation(value = "分页+高级查询")
    @Permission(name = "分页+高级查询",desc = "分页显示角色列表")
    public AjaxResult pageList(@RequestBody RoleQuery roleQuery){
        try {
            PageList<Role> pageList = roleService.getRolePageByKeyword(roleQuery);
            return AjaxResult.me().setResultObj(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setCode(201).setMessage(e.getMessage());
        }
    }

    /**
    * @author Sangyy
    * 新增或修改角色
    */
    @PutMapping
    @ApiOperation(value = "新增或修改角色")
    @Permission(name = "新增或修改角色",desc = "新增或修改角色信息")
    public AjaxResult insertOrUpdateRole(@RequestBody Role role){
        try {
            Long id = role.getId();
            boolean flag;
            if(id == null){
                flag = roleService.insert(role);
            }else {
                flag = roleService.update(role);
            }
            if(flag){
                return AjaxResult.me();
            }
            return AjaxResult.me().setMessage("操作失败！").setCode(201);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败！"+e.getMessage()).setCode(201);
        }

    }

    /**
    * @author Sangyy
    * 通过id删除角色
    */
    @ApiOperation(value = "通过id删除角色")
    @DeleteMapping("/{id}")
    @Permission(name = "删除角色",desc = "通过id删除角色")
    public AjaxResult deleteById(@PathVariable Long id){
        boolean b = roleService.deleteById(id);
        if(b){
            return AjaxResult.me();
        }
        return AjaxResult.me().setMessage("操作失败！").setCode(201);
    }
    /**
    * @author Sangyy
    * 批量删除角色
    */
    @ApiOperation(value = "批量删除角色")
    @DeleteMapping("batchDelete")
    @Permission(name = "批量删除角色",desc = "批量删除角色")
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        roleService.batchDelete(ids);
        return AjaxResult.me();
    }
}
